import { _decorator, Component, instantiate, Label, Node, Prefab } from 'cc';
import { app, GUI } from './App';
import { NActionServer } from '../../../../extensions/ngame/assets/ngame/action/core/NActionServer';
import { JNGame } from '../../../../extensions/ngame/assets/ngame/JNGame';
import NGameMessage from '../../../../extensions/ngame/assets/ngame/util/NGameMessage';
import { JNFrameInfo, JNSyncFrameEvent } from '../../../../extensions/ngame/assets/ngame/sync/frame/JNSyncFrame';
import { JNSyncAction } from '../../../../extensions/ngame/assets/ngame/sync/JNSyncAction';
import { JNSyncMessage } from '../../../../extensions/ngame/assets/ngame/sync/JNSyncMessage';
const { ccclass, property } = _decorator;

@ccclass('UIDemo')
export class UIDemo extends Component {

    //UI层
    @property(Node)
    ui:Node;

    //世界
    @property(Prefab)
    worldPrefab:Prefab;

    //世界
    @property(Node)
    world:Node;

    //显示帧数
    @property(Label)
    frameText:Label;

    async onLoad() {

        console.log("this.ui.position",this.ui.position)

        //监听帧同步
        app.event.on(JNSyncFrameEvent.CLEAR,this.clear,this);
        app.event.on(JNSyncFrameEvent.CREATE,this.create,this);

        app.layer.bind(this.ui);
        await JNGame.Init(app);
        app.socket.Send(NActionServer.PING);

        app.layer.Open(GUI.ViewDemo);
        console.log(NGameMessage.getIns().getType("JNFrameInfo"));

        //发生帧同步开始
        app.socket.Send(JNSyncAction.NSyncFrameStart);

        //监听帧回调
        app.socket.on(JNSyncAction.NSyncFrameBack,this.onFrameBack,this,"JNFrameInfo");

        console.log(app.api.defaults);

        //开始同步
        app.sync.onStart();

        app.api.get("/sync/frame",{
            responseType:'arraybuffer'
        }).then(res => {
            console.log(app.proto.getType(JNSyncMessage.JNFrameInfos).decode(new Uint8Array(res.data as ArrayBuffer)))
        }).catch(res => console.log(res))

        app.api.get("/sync/hello").then(res => {
            console.log(res);
        }).catch(res => console.log(res))

    }

    //清除世界
    clear(){
        this.world.removeAllChildren();
    }

    //创建世界
    create(){
        this.world.addChild(instantiate(this.worldPrefab))
    }

    update(deltaTime: number) {
        this.frameText.string = `${app.sync.nLocalFrame}_${app.sync.nFrameRun}`;
        app.sync.update(deltaTime);
    }

    onFrameBack(info:JNFrameInfo){
        app.sync.addFrame(info,true);
    }

}


